package is.server.controller.session.local;

import is.common.interfaces.Command;
import is.common.interfaces.DeactivationNeededThread;
import is.common.util.Regex;
import is.server.Main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Provides user session console (only root console supported in this release)
 *
 * @author aspr0
 *         Date: 08.04.12
 *         Time: 22:16
 */
public class LocalSessionThread extends Thread implements DeactivationNeededThread
{
    private boolean consoleActive;

    public LocalSessionThread()
    {
        consoleActive = true;
    }

    public void run()
    {
        Main.getController().getUserInterface().exposeConnectionEstablished();

        BufferedReader isr = new BufferedReader(new InputStreamReader(System.in));

        while (consoleActive)
        {
            Main.getController().getUserInterface().printInvitation();

            try
            {
                String requestSource = isr.readLine();

                /* no input to console - thread is stopping, break cycle */
                if (requestSource == null)
                {
                    break;
                }

                /* if string is empty or contain spaces symbols only */
                if (Regex.stringMatches(requestSource, "\\s*"))
                {
                    continue;
                }

                String[] request = requestSource.split(" ");

                Command command = CommandFactory.newInstance(request);
                command.execute();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void deactivate()
    {
        consoleActive = false;
    }
}
